package com.easyadmin.modules.job.schedule;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.easyadmin.common.quartz.base.BaseQuartz;
import com.easyadmin.modules.stock.domain.SysStockMessage;
import com.easyadmin.modules.stock.mapper.SysStockMessageDao;
import com.easyadmin.modules.stock.service.SysStockMessageServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.io.IOException;
import java.util.*;
import java.time.format.DateTimeFormatter;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Component("MessageTask")
public class MessageTask implements BaseQuartz {


    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    SysStockMessageDao sysStockMessageDao;
    @Autowired
    SysStockMessageServer sysStockMessageServer;


    @Override
    public void run(String params) throws Exception {

        LocalDateTime maxTime =sysStockMessageDao.selectList(new QueryWrapper<SysStockMessage>()).stream()
                .map(SysStockMessage::getMessageTime)
                .filter(Objects::nonNull)
                .max(LocalDateTime::compareTo)
                .orElse(null); // 如果没有值则返回null

        LocalDate today = LocalDate.now();
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 转换为字符串
        String todayStr = today.format(formatter);
        String url = "http://www.jin10.com";
        try {
            Document document = Jsoup.connect(url)
                    .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
                    .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                    .header("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
                    .header("Accept-Encoding", "gzip, deflate")
                    .header("Connection", "keep-alive")
                    .header("Upgrade-Insecure-Requests", "1")
                    .timeout(15000)
                    .get();
            System.out.println("=== 金十网站详细分析 ===");
            System.out.println(document.toString());
            // 尝试查找常见的信息容器
            String[] selectors = {
                    ".flash",".is-important"
            };
            List<SysStockMessage> list=new ArrayList<>();
            for (String selector : selectors) {
                Elements elements = document.select(selector);
                if (!elements.isEmpty()) {
                    //System.out.println("\n选择器 '" + selector + "' 找到 " + elements.size() + " 个元素:");
                    //for (int i = 0; i < Math.min(elements.size(), 3); i++) {
                    for (int i = 0; i < elements.size(); i++) {
                        Element el = elements.get(i);
                        Elements times = el.select(".item-time");
                        Elements title = el.select(".right-common-title");
                        Elements content = el.select(".flash-text");
                        /*System.out.println("22222222222222222222222222222222222");
                        System.out.println(times.text());
                        System.out.println(title.text());
                        System.out.println(content.text());*/
                        Elements important = el.select(".is-important");

                        DateTimeFormatter formatters = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                        // 解析字符串为LocalDateTime
                        LocalDateTime localDateTime = LocalDateTime.parse(todayStr+" "+times.text().toString(), formatters);

                        String titles=null;
                        if(StringUtils.isBlank(title.text())){
                            titles=content.text();
                        }else {
                            titles=title.text();
                        }
                        int result = maxTime.compareTo(localDateTime);

                        if(StringUtils.isNotBlank(title.text()) &&  StringUtils.isNotBlank(content.text())
                                &&  result < 0 && !title.text().contains("VIP")){
                            SysStockMessage message=new SysStockMessage();
                            message.setMessageName(titles);
                            message.setCreateTime(new Date());
                            message.setMessageDesc(content.text());
                            if(important.size()>0){
                                message.setImporFlag("1");
                            }
                            message.setMessageTime(localDateTime);
                            //去掉一些不必须要的东西
                            list.add(message);
                        }
                    }
                }
            }
            //过滤重复数据
            List<SysStockMessage> messageList =list.stream()
                    .collect(Collectors.toMap(
                            SysStockMessage::getMessageTime,
                            Function.identity(),
                            (existing, replacement) -> {
                                // 这里可以自定义冲突处理逻辑
                                // 比如保留创建时间更早的，或者根据其他字段判断
                                return existing;
                            }
                    ))
                    .values()
                    .stream()
                    .collect(Collectors.toList());
            sysStockMessageServer.saveBatch(messageList);
        } catch (IOException e) {
            System.out.println("错误: " + e.getMessage());
        }
    }

}
